<?php
// +----------------------------------------------------------------------
// | WWW.0771MC.COM 广西南宁市铭成龙毅网络科技有限公司 出品
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://WWW.0771MC.COM All rights reserved.
// +----------------------------------------------------------------------
// | Author: 铭成龙毅 <service@0771mc.com> <http://www.0771MC.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Think\Controller;
class CategoryController extends CommonController {

    public function index(){

        $cate = D('CategoryView')->order('category.sort')->select();
        $Category = new \Think\Category();
        $this->cate = $Category::unlimitedForLevel($cate, '&nbsp;&nbsp;&nbsp;&nbsp;', 0);
        $this->display();

    }

    //添加分类
    public function add() {
    
        if (IS_POST) {
            $this->addHandle();
            exit();
        }
        $pid = I('pid', 0, 'intval');
        $cate = M('category')->order('sort')->select();
        $Category = new \Think\Category();
        $this->cate = $Category::unlimitedForLevel($cate, '---',0);
        $this->mlist = M('model')->where(array('status' => 1))->order('sort')->select();  
        $this->styleListList = getFileFolderList(APP_PATH.C('DEFAULT_MODULE').'/View/'.C('cfg_theme').'/List/' , 2, 'List_*');
        $this->styleShowList = getFileFolderList(APP_PATH.C('DEFAULT_MODULE').'/View/'.C('cfg_theme').'/Show/' , 2, 'Show_*');
        $this->modelid=M('category')->where(array('id'=>$pid))->getField('modelid');
        $this->pid=$pid;
        $this->display();
    }

    //添加分类处理

    public function addHandle() {


        $data = I('post.', '');

        
        $data['name'] = trim($data['name']);
        $data['ename'] = trim($data['ename']);      
        $data['type'] = empty($data['type'])? 0 : intval($data['type']);

        if (isset($data['type']) && $data['type'] ==1 ) {
            $data['modelid'] = 0;
        }
        //M验证
        if (empty($data['name'])) {
            error('栏目名称不能为空！');
        }


        if (empty($data['ename'])) {
            $data['ename'] = get_pinyin(iconv('utf-8','gb2312//ignore',$data['name']),0);
        }elseif ($data['type'] == 0) {
            if (!ctype_alnum($data['ename'])) {
                error('别名只能由字母和数字组成，不能包含特殊字符！');
            }
        }   

        $data['ename']=strtolower($data['ename']);//转小写，否则前台转换出错

        $validate = array(
                array('ename','','别名已经存在！',0,'unique',1), 
            );

        $db=M('category');
        if (!$db->validate($validate)->create($data)) {
                $this->error($db->getError());
            }

        if ($db->add()) {
            getCategory(0,1);//清除栏目缓存
            getCategory(1,1);//清除栏目缓存
            getCategory(2,1);//清除栏目缓存
            //$this->success('添加栏目成功<script type="text/javascript" language="javascript">window.parent.get_cate();</script>',U('Category/index'));
            yes('添加成功！<script type="text/javascript" language="javascript">get_cate();</script>',true,'Category-index');
        }else {
            error('添加栏目失败');
        }
        
    }

    //修改分类
    public function edit() {

        if (IS_POST) {
            $this->editHandle();
            exit();
        }
        $id = I('id', 0, 'intval');
        $data = M('category')->find($id);
        if (!$data) {
            error('记录不存在');
        }
        $this->data = $data;
        $cate = M('category')->order('sort')->select();
        $Category = new \Think\Category();
        $this->cate = $Category::unlimitedForLevel($cate, '---',0);
        $this->mlist = M('model')->where(array('status' => 1))->order('sort')->select();        
        $this->styleListList = getFileFolderList(APP_PATH.C('DEFAULT_MODULE').'/View/'.C('cfg_theme').'/List/' , 2, 'List_*');
        
        $this->styleShowList = getFileFolderList(APP_PATH.C('DEFAULT_MODULE').'/View/'.C('cfg_theme').'/Show/' , 2, 'Show_*');
    
        $this->display();
    }



    //修改分类处理

    public function editHandle() {

        $data = I('post.', '');             
        $id = $data['id'] = intval($data['id']);
        $pid = $data['pid'];
        $data['name'] = trim($data['name']);
        $data['ename'] = trim($data['ename']);      
        $data['type'] = empty($data['type'])? 0 : intval($data['type']);

        if (isset($data['type']) && $data['type'] ==1 ) {
            $data['modelid'] = 0;
        }

        if ($id == $pid) {
            error('失败！不能设置自己为自己的子栏目，请重新选择父级栏目');
        }
        //M验证
        if (empty($data['name'])) {
            error('栏目名称不能为空！');
        }

        if (empty($data['ename'])) {
            $data['ename'] = get_pinyin(iconv('utf-8','gb2312//ignore',$data['name']),0);
        }elseif ($data['type'] == 0) {
            if (!ctype_alnum($data['ename'])) {
                error('别名只能由字母和数字组成，不能包含特殊字符！');
            }
        }
        /*
        if (M('category')->where(array('name' => $data['name'], 'id' => array('neq' , $id)))->find()) {
            $this->error('栏目名称已经存在！');
        }
        */
        $data['ename']=strtolower($data['ename']);//转小写，否则前台转换出错
       
        $validate = array(
                array('ename','','别名已经存在！',0,'unique',2), 
            );

        $db=M('category');
        if (!$db->validate($validate)->create($data)) {
                error($db->getError());
            }

        if (false !== $db->save($data)) {
            getCategory(0,1);//清除栏目缓存
            getCategory(1,1);
            getCategory(2,1);
            //$this->success('修改栏目成功<script type="text/javascript" language="javascript">window.parent.get_cate();</script>',U('Category/index'));
            yes('修改成功！<script type="text/javascript" language="javascript">get_cate();</script>',true,'Category-index');
        }else {
            error('修改栏目失败');
        }
        
    }

    //删除分类处理

    public function del() {

        $id = I('id', 0, 'intval');

        //查询是否有子类
        $childCate = M('category')->where(array('pid' => $id))->select();
        if ($childCate) {
            error('删除失败：请先删除本栏目下的子栏目');
        }

        //查询该栏目下是否有文章
        $mid=M('category')->where(array('id' => $id))->getField('modelid');
        $tableName=M('model')->where(array('id' => $mid))->getField('tablename');
        $dataNum=M($tableName)->where(array('cid' => $id))->field('id')->select();
        if ($dataNum) {
            error('删除失败：请先删除本栏目下的文章或产品',true,'',U(ucfirst($tableName) .'/index', array('pid'=>$id)));
        }

        if (M('category')->delete($id)) {
            //更新栏目缓存
            getCategory(0,1);
            getCategory(1,1);
            getCategory(2,1);
            //$this->success('删除栏目成功<script type="text/javascript" language="javascript">window.parent.get_cate();</script>',U('Category/index'));
            yes('删除成功！<script type="text/javascript" language="javascript">get_cate();</script>');
        }else {
            $this->error('删除栏目失败');
        }       
    }

    //批量更新排序
    public function sort() {
    
        foreach ($_POST as $k => $v) {
            if ($k == 'key') {
                continue;
            }
            M('category')->where(array('id'=>$k))->setField('sort',$v);
     
        }
        //$this->redirect('Category/index');
        yes();
    }

    //获取分类刷新主框架显示栏目列表
    public function getParentCate(){
        header("Content-Type:text/html; charset=utf-8");
        //权限验证获取哪些栏目
        $auth=new \Think\Auth();
        $groups=$auth->getGroups($_SESSION['aid']);

        if(!in_array($groups[0]['id'], C('ADMINISTRATOR'))){//超级管理员绕过
            $authed_group   =  getCategoryOfGroup($groups[0]['id'],1);//获取到授权访问的栏目
            //查询是否有子类的栏目，如果有子类的栏目却子类没有选择，则剔除。
            $Category = new \Think\Category();
            $cate = getCategory();
            for ($i=0; $i <count($authed_group) ; $i++) { 
                $is_have=$Category::getChilds($cate, $authed_group[$i]);
                if (!empty($is_have)) {
                    for ($k=0; $k <count($is_have) ; $k++) { 
                        $childCate_id[]=$is_have[$k]['id'];
                        for ($d=0; $d <count($childCate_id) ; $d++) { 
                            if (!in_array($childCate_id[$d],$authed_group)) {
                                unset($authed_group[$i]);
                            }
                        }
                    }
                }
            }
            //剔除有子类的栏目，但是子类却没有授权的栏目 结束
            $authed_group=implode(',',$authed_group);
            $where['category.id']=array('IN',$authed_group);
        }

        $where['pid']=0;
        $where['type']=0;

        $count = D('CategoryView')->where($where)->count();
		if($count==0){
			$menudoclist = array('count' => 1);//目的是为了清除前台的内容管理
		}else{
			$list = D('CategoryView')->where($where)->order('category.sort')->select();
	        $menudoclist = array('count' => $count);
	        foreach ($list as $v) {
	            if ($v['tablename']=="download" || $v['tablename']=="page") {
	                $url=U(ucfirst($v['tablename']) .'/index', array('pid'=>$v['id']));
	            }else{
	                $url=U('Article/index', array('pid'=>$v['id'],'model'=>$v['tablename']));
	            }
	            $menudoclist['list'][] = array(
	                'id' => $v['id'],               
	                'name' => $v['name'],       
	                'url' => $url
	            );
	        }
			//exit(json_encode($menudoclist));
		}
		exit(json_encode($menudoclist));

    }



}